package com.zxq.factory.utils;

import java.util.HashMap;

public class HexToAscii {
    /**
     * hash对照表
     */
    static HashMap<String,String> hexLink = new HashMap<>();
    static HashMap<String,String> asciiLink = new HashMap<>();
    static {
        hexLink.put("00","30");
        hexLink.put("01","31");
        hexLink.put("02","32");
        hexLink.put("03","33");
        hexLink.put("04","34");
        hexLink.put("05","35");
        hexLink.put("06","36");
        hexLink.put("07","37");
        hexLink.put("08","38");
        hexLink.put("09","39");
        hexLink.put("0A","41");
        hexLink.put("0B","42");
        hexLink.put("0C","43");
        hexLink.put("0D","44");
        hexLink.put("0E","45");
        hexLink.put("0F","46");
        //38 36 39 35 31 36 30 35 38 39 34 32 33 36 33
        //08 06  09 05  01 06  03 05 08 09 04 02 03 06 03
        asciiLink.put("30","00");
        asciiLink.put("31","01");
        asciiLink.put("32","02");
        asciiLink.put("33","03");
        asciiLink.put("34","04");
        asciiLink.put("35","05");
        asciiLink.put("36","06");
        asciiLink.put("37","07");
        asciiLink.put("38","08");
        asciiLink.put("39","09");
        asciiLink.put("41","0A");
        asciiLink.put("42","0B");
        asciiLink.put("43","0C");
        asciiLink.put("44","0D");
        asciiLink.put("45","0E");
        asciiLink.put("46","0F");

    }

    private static String _1asciiToHex(String ascii) {

        return asciiLink.get(ascii);
    }

    private static String _1hexToAscii(String hex) {

        return hexLink.get(hex);
    }



    public static String asciiToHex(String ascii) {
        StringBuilder asciiText = new StringBuilder();

        for(int i = 0; i < ascii.length() / 2; i++) {
            String ascIICode =  ascii.substring(2* i,2* i + 2);
            String hexCode = HexToAscii._1asciiToHex(ascIICode);
            asciiText.append(hexCode);
        }
        String hexFrameText  = asciiText.toString();

        return hexFrameText;
    }

    public static String hexToAscii(String hex) {
        StringBuilder ascIIText = new StringBuilder();
        for(int i = 0; i < hex.length() / 2 ; i++) {
            String hexCode =  hex.substring( 2 * i, 2 * i + 2);
            String ascIICode = HexToAscii._1hexToAscii(hexCode);
            ascIIText.append(ascIICode);
        }
        String hexFrameText  = ascIIText.toString();
        return hexFrameText;
    }










}
